package com.youi.web;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.youi.common.Common;
import com.youi.common.DelStatus;
import com.youi.common.SessionKey;
import com.youi.entity.Goods;
import com.youi.entity.Goodsandgoodscar;
import com.youi.entity.Goodscar;
import com.youi.entity.MarketAdvertisement;
import com.youi.entity.User;
import com.youi.exception.BusinessException;
import com.youi.manage.HttpRequestManage;
import com.youi.manage.HttpSessionManage;
import com.youi.model.GoodsAndAds;
import com.youi.service.GoodsService;
import com.youi.service.GoodsandgoodscarService;
import com.youi.service.GoodscarService;
import com.youi.service.MarketAdvertisementService;
import com.youi.service.UserService;
import com.youi.util.CommonInfoUtil;
import com.youi.util.JsonUtil;
import com.youi.util.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.IntStream;

/**
 * 商品信息控制层
 *
 * @author Administrator
 */
@RestController
public class GoodsController extends HttpRequestManage {

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private GoodscarService goodscarService;

    @Autowired
    private GoodsandgoodscarService goodsandgoodscarService;

    @Autowired
    private UserService userService;

    @Autowired
    private MarketAdvertisementService marketAdvertisementService;


    /**
     * M-7
     * 查询商品列表
     * <p>搜索<p/>
     */
    @RequestMapping(value = "/getGoods")
    public String getGoods(ModelMap modelMap, HttpServletRequest request) throws BusinessException, ParseException {
        Integer pageIndex = optInteger("pageIndex", request, 1);
        Integer pageNum = optInteger("pageNum", request, 10);
        String pms = optString("pms", request);
        Integer orderBy = optInteger("orderBy", request, 0);
        Integer sortType = optInteger("sortType", request, 0);

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("offset", (pageIndex - 1) * pageNum);
        params.put("rows", pageNum);
        params.put("pms", pms);
        params.put("orderBy", orderBy);
        if (sortType == 1) {
            params.put("des", Common.DESC);
        } else if (sortType == 2) {
            params.put("des", Common.ASC);
        } else {
            params.put("des", Common.DESC);
        }

        List<Goods> goodsList = goodsService.listGoodsByPage(params);
        if (CollectionUtils.isEmpty(goodsList)) {
            return JsonUtil.toJson(CommonInfoUtil.NULLDATA, "空数据");
        }

        Integer pageCount = goodsService.countListGoods(params);
        modelMap.put(CommonInfoUtil.PAGECOUNT, Page.getCount(pageCount, pageNum));
        modelMap.put(CommonInfoUtil.PAGEINDEX, pageIndex);
        modelMap.put(CommonInfoUtil.ALLCOUINT, pageCount);
        modelMap.put(CommonInfoUtil.DATA, goodsList);
        goodsService.getGoodsMsg(goodsList);
        return JsonUtil.toJson(CommonInfoUtil.SUCCESS, "操作完成", modelMap);
    }


    /**
     * 商品列表
     * <p>首页<p/>
     */
    @RequestMapping(value = "/listTopGoods")
    public String listTopGoods(ModelMap modelMap, HttpServletRequest request) throws BusinessException, ParseException {
        Integer pageIndex = optInteger("pageIndex", request, 1);
        Integer pageNum = optInteger("pageNum", request, 10);

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("offset", (pageIndex - 1) * pageNum);
        params.put("rows", pageNum);
        params.put("topShow", 1);

        List<Goods> goodsList = goodsService.listGoodsByPage(params);
        if (CollectionUtils.isEmpty(goodsList)) {
            return JsonUtil.toJson(CommonInfoUtil.NULLDATA, "空数据");
        }
        goodsService.getGoodsMsg(goodsList);
        Integer goodsCount = goodsList.size();

        // 商品中插入广告,每页商品数据插入一条广告
        MarketAdvertisement marketAdvertisement = getAdvertisementForOnePage(pageIndex);

        //重新组装返回的数据结构
        List<GoodsAndAds> resultList = Lists.newArrayList();
        IntStream.range(0, goodsCount).forEach(i -> {
            GoodsAndAds goods = new GoodsAndAds();
            goods.setType(1);
            goods.setGoods(goodsList.get(i));
            resultList.add(goods);

            if (marketAdvertisement == null) {
                return;
            }

            if (pageIndex == 1) {
                //第一页商品，在第5个位置添加广告
                if (i == 4) {
                    GoodsAndAds ads = new GoodsAndAds();
                    ads.setType(2);
                    ads.setAdvertisement(marketAdvertisement);
                    resultList.add(ads);
                }
            } else {
                //其他页，在第2个位置添加
                if (i == 1) {
                    GoodsAndAds ads = new GoodsAndAds();
                    ads.setType(2);
                    ads.setAdvertisement(marketAdvertisement);
                    resultList.add(ads);
                }
            }
        });

        Integer pageCount = goodsService.countListGoods(params);
        modelMap.put(CommonInfoUtil.PAGECOUNT, Page.getCount(pageCount, pageNum));
        modelMap.put(CommonInfoUtil.PAGEINDEX, pageIndex);
        modelMap.put(CommonInfoUtil.ALLCOUINT, pageCount);
        //modelMap.put(CommonInfoUtil.DATA, goodsList);
        modelMap.put(CommonInfoUtil.DATA, resultList);
        return JsonUtil.toJson(CommonInfoUtil.SUCCESS, "操作完成", modelMap);
    }

    /**
     * 获取某个商品页的一个广告
     *
     * @param pageIndex
     * @return
     */
    private MarketAdvertisement getAdvertisementForOnePage(Integer pageIndex) {
        Map<String, Object> adsParams = Maps.newHashMap();
        adsParams.put(Common.DELSTATUS, DelStatus.NODEL);
        adsParams.put(Common.STATUS, 1);
        //1-首页banner,2-商品插播
        adsParams.put("position", 2);
        adsParams.put("currentDate", new Date());
        adsParams.put("offset", (pageIndex - 1) * 1);
        adsParams.put("rows", 1);
        List<MarketAdvertisement> adsList = marketAdvertisementService.listAdvertisementByParam(adsParams);
        return CollectionUtils.isEmpty(adsList) ? null : adsList.get(0);
    }

    /**
     * 查询商品信息
     */
    @RequestMapping(value = "/getGoodsInfoById")
    public String getGoodsInfoById(ModelMap modelMap, HttpServletRequest request) throws BusinessException {
        User user = (User) HttpSessionManage.getAttribute(request, SessionKey.USER);
        Long id = getLong("id", request);
        Goods goods = goodsService.get(id);
        if (goods == null) {
            return JsonUtil.toJson(CommonInfoUtil.NULLDATA, "空数据");
        }
        goodsService.getGoodsInfoById(goods);
        return JsonUtil.toJson(CommonInfoUtil.SUCCESS, "操作完成", goods);
    }

    /**
     * M-8
     * 查询商品详情
     */
    @RequestMapping(value = "/getGoodsById")
    public String getGoodsById(ModelMap modelMap, HttpServletRequest request) throws BusinessException {
        User user = (User) HttpSessionManage.getAttribute(request, SessionKey.USER);
        Long id = getLong("id", request);
        Goods goods = goodsService.get(id);
        if (goods == null) {
            return JsonUtil.toJson(CommonInfoUtil.NULLDATA, "空数据");
        }
        goodsService.getGoodsMsg(goods, user);
        return JsonUtil.toJson(CommonInfoUtil.SUCCESS, "操作完成", goods);//jsonObject	json对象
    }

    /**
     * M-39
     * 检测购物车是否有商品
     */
    @RequestMapping(value = "/checkisGoodsCar")
    public String checkisGoodsCar(ModelMap modelMap, HttpServletRequest request) throws BusinessException {
        String token = getString(Common.TOKEN, request);
        Long id = getLong("id", request);

        Map<String, Object> prams = new HashMap<String, Object>();
        prams.put(Common.DELSTATUS, DelStatus.NODEL);
        prams.put(Common.TOKEN, token);
        User user = userService.getByParam(prams);

        Goods goods = goodsService.get(id);
        if (user != null) {
            Map<String, Object> params = new HashMap<String, Object>();
            params.put(Common.DELSTATUS, DelStatus.NODEL);
            params.put(Common.USERID, user.getId());
            Goodscar goodscar = goodscarService.getByParam(params);
            if (goodscar == null) {
                goodscarService.saveOrUpdate(new Goodscar(user.getId(), 0.00));
                goods.setIsGoodsCar(0);
            }
            params = new HashMap<String, Object>();
            params.put(Common.DELSTATUS, DelStatus.NODEL);
            params.put("goodscarId", goodscar.getId());
            List<Goodsandgoodscar> goodsandgoodscars = goodsandgoodscarService.getByParams(params);
            if (goodsandgoodscars == null || goodsandgoodscars.size() == 0) {
                goods.setIsGoodsCar(0);
            } else {
                goods.setIsGoodsCar(1);
            }
        } else {
            goods.setIsGoodsCar(0);
        }
        goodsService.getGoodsMsg(goods, user);
        modelMap.put("isGoodsCar", goods.getIsGoodsCar());
        return JsonUtil.toJson(CommonInfoUtil.SUCCESS, "操作完成", modelMap);
    }

    /**
     * M-31
     * 修改未开售商品状态
     */
    @Deprecated
    @RequestMapping(value = "/editGoodsStatus")
    public String editGoodsStatus(ModelMap modelMap, HttpServletRequest request) throws BusinessException {
        Long id = getLong("id", request);
        Goods goods = goodsService.get(id);
        if (goods == null && goods.getStatus() != 4) {
            return JsonUtil.toJson(CommonInfoUtil.NULLDATA, "商品不存在或非未出售商品");
        }
        if (goods.getGmtStart().getTime() < System.currentTimeMillis()) {
            return JsonUtil.toJson(CommonInfoUtil.NOOPPMS, "开始时间未到无法修改商品状态");
        }
        goods.setStatus(1);
        goodsService.saveOrUpdate(goods);
        return JsonUtil.toJson(CommonInfoUtil.SUCCESS, "操作完成");
    }

    /**
     * 查询所有商品信息
     *
     * @param modelMap
     * @param request
     * @return
     */
    @RequestMapping(value = "/getAllGoods")
    public String getAllGoods(ModelMap modelMap, HttpServletRequest request) throws BusinessException {
        List<Goods> goodsList = goodsService.getByParams(null);
        if (goodsList == null || goodsList.size() == 0) {
            return JsonUtil.toJson(CommonInfoUtil.NULLDATA, "空数据");
        }
        return JsonUtil.toJson(CommonInfoUtil.SUCCESS, "操作完成", goodsList);
    }
}